package com.chj.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chj.dao.DictionaryEntityMapper;
import com.chj.entity.DictionaryEntity;
import com.chj.entity.OrderEntity;
import com.chj.entity.UserEntity;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class DictionaryService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DictionaryEntityMapper dictionaryMapper;

    @Transactional
    public long addOne(DictionaryEntity dictionary) {
         this.dictionaryMapper.insert(dictionary);
        return dictionary.getId();
    }

    public List<DictionaryEntity> getList() {
        return dictionaryMapper.selectByMap(null);
    }

    public Page<DictionaryEntity> getPage() {
        Page<DictionaryEntity> page = new Page<>();
        return dictionaryMapper.selectPage(page, Wrappers.emptyWrapper());
    }

    @Transactional
    @GlobalTransactional(name = "derek-test-create-order",rollbackFor = Exception.class)
    public long add(DictionaryEntity dictionary,  int index) {
        log.info("****************>>>>> {}", RootContext.getXID());
        this.dictionaryMapper.insert(dictionary);
        long uuid = dictionary.getId();
        log.info("-----DictionaryService---> {}", uuid);
        UserEntity userEntity = new UserEntity();
        if(index % 2 == 0){
            userEntity.setUserNum("DEREK" + uuid);
            userEntity.setNickName("NickName" + uuid);
        }
        userEntity.setCreatedDate(new Date());
        userEntity.setLastUpdatedDate(new Date());

        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderNum(uuid);
        orderEntity.setUserNum("DEREK" + uuid);
        orderEntity.setTotalPrice(new BigDecimal(123));

        // order 成功
        restTemplate.postForObject("http://localhost:8102/order", orderEntity, String.class);

        // user可能会失败
        restTemplate.postForObject("http://localhost:8101/user", userEntity, String.class);
        return dictionary.getId();
    }


}
